package com.blog.cmrpersonalblog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.cmrpersonalblog.entity.SysUserRole;
import com.blog.cmrpersonalblog.mapper.SysUserRoleMapper;
import com.blog.cmrpersonalblog.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关联服务实现类
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRolesToUser(Long userId, List<Long> roleIds) {
        try {
            // 先删除用户的所有角色关联
            removeAllRolesFromUser(userId);
            
            // 如果角色列表不为空，则添加新的角色关联
            if (roleIds != null && !roleIds.isEmpty()) {
                List<SysUserRole> userRoles = roleIds.stream()
                        .map(roleId -> {
                            SysUserRole userRole = new SysUserRole();
                            userRole.setUserId(userId);
                            userRole.setRoleId(roleId);
                            return userRole;
                        })
                        .collect(Collectors.toList());
                
                return baseMapper.insertBatch(userRoles) > 0;
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("分配角色失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAllRolesFromUser(Long userId) {
        try {
            return baseMapper.deleteByUserId(userId) >= 0;
        } catch (Exception e) {
            throw new RuntimeException("移除用户角色失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAllUsersFromRole(Long roleId) {
        try {
            return baseMapper.deleteByRoleId(roleId) >= 0;
        } catch (Exception e) {
            throw new RuntimeException("移除角色用户失败", e);
        }
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        return baseMapper.selectRoleIdsByUserId(userId);
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        return baseMapper.selectUserIdsByRoleId(roleId);
    }

    @Override
    public boolean hasRole(Long userId, Long roleId) {
        return baseMapper.countByUserIdAndRoleId(userId, roleId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeRolesByUserIds(List<Long> userIds) {
        try {
            if (userIds == null || userIds.isEmpty()) {
                return true;
            }
            return baseMapper.deleteByUserIds(userIds) >= 0;
        } catch (Exception e) {
            throw new RuntimeException("批量移除用户角色失败", e);
        }
    }
}
